<?php
namespace app\index\controller;

use think\Controller;
use app\index\model\Vercode;
use app\index\model\User;
use app\index\model\Replay as ReplayModel;
use think\Loader;
use app\index\model\Category;
use app\index\model\Question;
use app\index\model\ReplayZan;
use app\index\model\Msg;
use think\Db;
/**
 * 
 */
class Replay extends Common
{
    
    /**
     * [addpost 增加回复]
     * @return [type] [description]
     */
    public function add()
    { 
         
        //接数据
        $data = input('post.');
        //验证
        $validate = Loader::validate('replay');

        if(!$validate->check($data)){
            $this->error($validate->getError());
        }

        $data['uid'] = session('uid');

        $data['ctime'] = time();

        //往数据库增加数据 
        $res = (new ReplayModel);

        $res->data($data);
        
        $res->save();

        if(!$res){
            $this->error('回复失败');
        }else{

            $data['ctime'] = time();

            $data['qid'] = $data['qid'];

            $data['type']='replay';

            $data['suid'] = session('uid');

            $question = Question::get($data['qid']);

            $data['duid'] = $question->uid;

            $data['rid'] = $res->rid;

            $msg = new Msg();

            $msg->data($data);

            $msg->save();

            (new Question)->where('qid', $data['qid'])->setInc('replay');

            $this->success('回复成功');
        }
    }
    /**
     * [zan 点赞]
     * @return [type] [description]
     */
    public function zan()
    {
        $data = input('post.');

        $data['uid'] = session('uid');

        $res = ReplayZan::get($data);

        if($res){

            ReplayZan::destroy($data);

            (new ReplayModel)->where('rid', $data['rid'])->setDec('zan_num');

            $this->success('取消点赞');

        }else{

            $data['ctime'] = time();

            $user = new ReplayZan;
            $user->data($data);
            $res = $user->save();


            $Replay = ReplayModel::get($data['rid']);

            $data['ctime'] = time();

            $data['qid'] = $Replay->qid;

            $data['type']='zan';

            $data['suid'] = session('uid');

            $data['rid'] = $data['rid'];

            $data['duid'] = $Replay->uid;

            $msg = new Msg();

            $msg->data($data);

            $msg->save();

            (new ReplayModel)->where('rid', $data['rid'])->setInc('zan_num');

            $this->success('点赞成功');
        }
    }

}